#include "myclient.h"
#include <QHostAddress>
MyClient::MyClient(QObject *parent):QObject(parent)
{
    m_tcp = new QTcpSocket(this);
    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
        QByteArray byteArray=m_tcp->readAll();
        QString data = QString::fromUtf8(byteArray);
        qDebug()<<"client收到消息";
        qDebug()<<"收到： "<<byteArray;
        qDebug()<<"收到： "<<data;
        emit mmrecived(data);
    });
}

void MyClient::connectServer(unsigned short port,QString ip){
    //m_tcp=new QTcpSocket;
    m_tcp->connectToHost(QHostAddress(ip),port);
    //如果连接成功传信号给主线程
    //连接成功触发connectOK信号，connected是状态信号
    connect(m_tcp,&QTcpSocket::connected,this,&MyClient::connectOK);
    connect(m_tcp, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::errorOccurred), this, &MyClient::displayError);
    //连接失败清除资源
    //connect(m_tcp, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
//    connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
//        m_tcp->close();
//        m_tcp->deleteLater();
//        emit gameover();//触发gameover信号
//    });
}
void MyClient::sendm(QByteArray mm){
    m_tcp->write(mm);
    m_tcp->waitForBytesWritten();
    qDebug()<<"client发送消息";
    emit mmsend();
}
void MyClient::displayError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "Error: " << m_tcp->errorString();
}
